package com.cn.wanxi.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.annotaion.Controller;
import com.cn.wanxi.annotaion.RequestMapping;
import com.cn.wanxi.listenner.WebApplicationContextUtils;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

//@Controller
//@RequestMapping("/spring/user/findAll")
@WebServlet("/spring/user/findAll")
public class UserController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获得spring容器的应用上下文
//        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//        ApplicationContext applicationContext= (ApplicationContext) this.getServletContext().getAttribute("applicationContext");
      ApplicationContext applicationContext= WebApplicationContextUtils.getWebApplicationContextUtils(this.getServletContext());
        IUserService iUserService = applicationContext.getBean(UserServiceImpl.class);
        List<UserModel> list = iUserService.findAllForSpring(new UserModel());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", list);
        resp.getWriter().println(jsonObject);
    }
}
